package com.qf.sl.youshare.adapters;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.qf.sl.youshare.Constants;
import com.qf.sl.youshare.R;
import com.qf.sl.youshare.model.GoodsCart;
import com.qf.sl.youshare.utils.FileCache;
import com.qf.sl.youshare.utils.ImageCache;
import com.qf.sl.youshare.utils.ImageLoader;

import java.util.LinkedList;

/**
 * Created by IDEA
 * User : sl
 * on 2015/2/25.
 * 20:44
 */
public class CartAdapter extends BaseAdapter {

    private LayoutInflater inflater;
    private LinkedList<GoodsCart> goodsCarts;

    /**
     * 设置外部事件处理监听器，用于处理，增加，减少，删除的操作
     * 设置成员变量的目的是让外部监听器计算总金额
     */

    private View.OnClickListener operationListener;

    /**
     * 用于处理购物车项目的选中与未选中的状态
     */
    private CompoundButton.OnCheckedChangeListener checkedChangeListener;

    public CartAdapter(Context context, LinkedList<GoodsCart> goodsCarts) {
        if (context != null) {
            inflater = LayoutInflater.from(context);
        }else {
            throw new IllegalArgumentException("context must not null");
        }
        this.goodsCarts = goodsCarts;
    }

    @Override
    public int getCount() {
        int ret = 0;
        if (goodsCarts != null) {
            ret = goodsCarts.size();
        }
        return ret;
    }

    @Override
    public Object getItem(int position) {
        Object ret = null;
        if (goodsCarts != null) {
            ret = goodsCarts.get(position);
        }
        return ret;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View ret = null;

        if (convertView != null) {
            //TODO 如果一个 ListView 显示不同的布局，如何处理？
            ret = convertView;
        }else {
            ret = inflater.inflate(R.layout.item_cart, parent, false);
        }

        ViewHolder holder = (ViewHolder) ret.getTag();

        if (holder == null) {
            holder = new ViewHolder();

            holder.checkBoxHolder = (CheckBox) ret.findViewById(R.id.item_cart_checked);
            holder.imageHolder = (ImageView) ret.findViewById(R.id.item_cart_icon);
            holder.titleHolder = (TextView) ret.findViewById(R.id.item_cart_title);
            holder.priceHolder = (TextView) ret.findViewById(R.id.item_cart_price);
            holder.deleteHolder = (TextView) ret.findViewById(R.id.item_cart_delete);
            holder.countHolder = (EditText) ret.findViewById(R.id.item_cart_count);
            //TODO 需要进行输入内容的观察，每次输入，进行数据的设置
            holder.subBtnHolder = (Button) ret.findViewById(R.id.item_cart_sub);
            holder.addBtnHolder = (Button) ret.findViewById(R.id.item_cart_add);

            ret.setTag(holder);
        }

        holder.checkBoxHolder.setTag(position);
        holder.deleteHolder.setTag(position);
        holder.countHolder.setTag(position);
        holder.subBtnHolder.setTag(position);
        holder.addBtnHolder.setTag(position);

        final EditText text = holder.countHolder;

        holder.countHolder.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String string = s.toString();//获取文本输入框的实际内容
                if (string.length() == 0){
                    string = "0";
                }
                int count = Integer.parseInt(string);
                Object tag = text.getTag();
                if (tag != null) {
                    if (tag instanceof Integer){
                        int poi = (Integer)tag;
                        GoodsCart goodsCart = goodsCarts.get(poi);
                        goodsCart.setCount(count);
                        notifyDataSetChanged();
                        //TODO 检查在 ListView 在输入的
                    }
                }
            }
        });


        final GoodsCart goodsCart = goodsCarts.get(position);

        /**
         * 商品缩略图的加载
         */
        String goods_thumb = goodsCart.getGoods_thumb();
        if (goods_thumb != null && goods_thumb.length() > 0) {
            if (!goods_thumb.startsWith("http://") && !goods_thumb.startsWith("https://")){
                goods_thumb = Constants.IMAGE_SERVER + goods_thumb;
            }

            holder.imageHolder.setTag(goods_thumb);

            holder.imageHolder.setImageResource(R.drawable.product_default);

            ImageCache imageCache = ImageCache.getInstance();

            Bitmap image = imageCache.getImage(goods_thumb);
            if (image != null) {
                holder.imageHolder.setImageBitmap(image);
            }else {
                FileCache fileCache = FileCache.getInstance();
                byte[] bytes = fileCache.getFileContent(goods_thumb);
                if (bytes != null && bytes.length > 0) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    holder.imageHolder.setImageBitmap(bitmap);
                    imageCache.putImage(goods_thumb,bitmap);
                }else {
                    ImageLoader task = new ImageLoader(holder.imageHolder);
                    task.execute(goods_thumb);
                }
            }
        }

        /**
         * CheckBox 的选中与否
         */
        boolean checked = goodsCart.isChecked();
        holder.checkBoxHolder.setChecked(checked);

        /**
         * 购物车商品名称的显示
         */
        String productName = goodsCart.getGoods_name();
        holder.titleHolder.setText(productName);

        /**
         * 购物车商品价格的显示
         */
        String price = goodsCart.getGoods_price();
        holder.priceHolder.setText(price);

        /**
         * 购物车商品 CheckBox 的选中与否
         */

        if (checkedChangeListener != null) {
            holder.checkBoxHolder.setOnCheckedChangeListener(checkedChangeListener);
        }

//        System.out.println("checked = " + checked);

        /**
         * 购物车商品减少按钮的实现
         */
        if (operationListener != null) {
            holder.subBtnHolder.setOnClickListener(operationListener);
        }

        /**
         * 购物车商品增加按钮的实现
         */
        if (operationListener != null) {
            holder.addBtnHolder.setOnClickListener(operationListener);
        }

        if (operationListener != null) {
            holder.deleteHolder.setOnClickListener(operationListener);
        }

        int count = goodsCart.getCount();
        holder.countHolder.setText(Integer.toString(count));


        return ret;
    }

    public void setOperationListener(View.OnClickListener operationListener) {
        this.operationListener = operationListener;
    }

    public void setCheckedChangeListener(CompoundButton.OnCheckedChangeListener checkedChangeListener) {
        this.checkedChangeListener = checkedChangeListener;
    }

    private class ViewHolder{
        public CheckBox checkBoxHolder;
        public ImageView imageHolder;
        public TextView titleHolder;
        public TextView priceHolder;
        public TextView deleteHolder;
        public EditText countHolder;
        public Button subBtnHolder;
        public Button addBtnHolder;
    }
}
